﻿using System.Text.Json;

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;

using SkiaSharp;

using XServer.Managers;
using XServer.Models.Http;
using XServer.Models.OSS;
using XServer.Systems;
using XServer.Utility;
using XServer.Utility.Pools;

namespace XServer.Controllers
{
    [ApiController]
    [Route("/pictures")]
    public class PictureController : ControllerBase
    {
        private readonly ILogger<PictureController> _logger;
        private readonly ThreadPoolFactory _threadPoolFactory;

        public PictureController(ILogger<PictureController> logger, ThreadPoolFactory threadPoolFactory)
        {
            _logger = logger;
            _threadPoolFactory = threadPoolFactory;
        }

        /// <summary>
        /// 获取图片列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("/pictures/list")]
        public IActionResult GetPictureList()
        {
            _logger.LogDebug("获取图片列表");

            var config = OssManager.Instance.GetConfig();
            var files = OssHelper.ListObject(config) ?? [];

            List<string> list = [];
            foreach (string file in files)
            {
                list.Add(Path.GetFileName(file));
            }

            return Content(JsonSerializer.Serialize(list), "application/json");
        }

        /// <summary>
        /// 下载原图
        /// </summary>
        /// <param name="imageName"></param>
        /// <returns></returns>
        [HttpGet("/pictures/{imageName}")]
        public IActionResult GetPicture([FromRoute] string imageName)
        {
            _logger.LogDebug($"文件名: {imageName}");

            string filePath = CommonTools.GetFile(imageName, _logger);
            if (filePath == "Error")
            {
                _logger.LogError("图片资源不存在");
                return Problem(
                    type: "Resource Not Found",
                    title: "文件不存在",
                    detail: $"文件'{imageName}'未找到",
                    statusCode: 404
                );
            }

            byte[] imageBytes;
            imageBytes = System.IO.File.ReadAllBytes(filePath);

            return File(imageBytes, CommonTools.GetMimeType(filePath));
        }

        /// <summary>
        /// 获取缩略图
        /// </summary>
        /// <param name="imageName"></param>
        /// <param name="desiredWidth"></param>
        /// <param name="desiredHeight"></param>
        /// <returns></returns>
        [HttpGet("/pictures/thumbnail/{imageName}")]
        public IActionResult GetThumbnailPicture([FromRoute] string imageName, int desiredWidth, int desiredHeight)
        {
            _logger.LogDebug($"文件名: {imageName}, 宽: {desiredWidth}, 高: {desiredHeight}");

            string filePath = CommonTools.GetFile(imageName, _logger);
            if (filePath == "Error")
            {
                _logger.LogError("图片资源不存在");
                return Problem(
                    type: "Resource Not Found",
                    title: "文件不存在",
                    detail: $"文件'{imageName}'未找到",
                    statusCode: 404
                );
            }

            try
            {
                byte[] thumbBytes = PictureHelper.GenerateThumbnailNew(filePath, desiredWidth, desiredHeight);
                return File(thumbBytes, "image/jpeg");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                return Problem(
                    type: "ImageDecodingError",
                    title: "图片解码错误",
                    detail: $"图片解码错误",
                    statusCode: 500
                );
            }
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("/pictures/upload/{fileName}")]
        public async Task<IActionResult> UploadPicture([FromRoute] string fileName, IFormFile file)
        {
            _logger.LogDebug($"文件名: {fileName}");

            if (file == null || file.Length == 0)
            {
                return BadRequest("未上传文件");
            }

            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images", fileName);

            // 如果图片存在则直接返回OK
            if (CommonTools.FileExist(filePath))
            {
                return Ok();
            }

            // 将图片缓存到服务器
            using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                await file.CopyToAsync(stream);
            }

            // 上传图片到OSS服务器
            bool res = CommonTools.UploadFile(filePath, _logger);
            if (res)
            {
                return Ok();
            }
            else
            {
                return Problem();
            }
        }
    }
}
